'use strict';

const path = require('path');
const fs = require('fs');

// 只运行缺失的迁移
async function migrateMissing() {
  try {
    console.log('开始检查并运行缺失的迁移...');
    
    // 使用Sequelize连接数据库
    const { Sequelize } = require('sequelize');
    
    const dbConfig = {
      host: process.env.MySqlHost || '127.0.0.1',
      port: process.env.MySqlPort || 3306,
      user: process.env.MySqlUsername || 'root',
      password: process.env.MySqlPassword || '302108jw302',
    };
    
    const dbName = process.env.MySqlDatabase || 'wardrobe_db';
    
    const sequelize = new Sequelize(dbName, dbConfig.user, dbConfig.password, {
      host: dbConfig.host,
      port: dbConfig.port,
      dialect: 'mysql',
      logging: console.log,
      define: {
        raw: true,
        underscored: true,
        charset: 'utf8mb4',
        timestamps: true,
        paranoid: true,
        freezeTableName: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
      },
      dialectOptions: {
        dateStrings: true,
        typeCast: true,
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci',
      },
      timezone: '+08:00',
    });
    
    // 测试连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查哪些表已经存在
    const [results] = await sequelize.query('SHOW TABLES');
    const existingTables = results.map(row => Object.values(row)[0]);
    console.log('现有表:', existingTables);
    
    // 需要创建的表和对应的迁移文件
    const tableMigrations = {
      'user_preferences': '007-create-user-preferences.js',
      'clothing_tags': '008-create-clothing-tags.js',
      'outfit_items': '009-create-outfit-items.js',
    };
    
    // 执行缺失表的迁移
    const migrationsDir = path.join(__dirname, 'migrations');
    
    for (const [tableName, migrationFile] of Object.entries(tableMigrations)) {
      if (!existingTables.includes(tableName)) {
        console.log(`表 ${tableName} 不存在，执行迁移: ${migrationFile}`);
        
        const migrationPath = path.join(migrationsDir, migrationFile);
        if (fs.existsSync(migrationPath)) {
          const migration = require(migrationPath);
          await migration.up(sequelize.getQueryInterface(), Sequelize);
          console.log(`迁移 ${migrationFile} 执行成功`);
        } else {
          console.log(`迁移文件 ${migrationFile} 不存在`);
        }
      } else {
        console.log(`表 ${tableName} 已存在，跳过迁移`);
      }
    }
    
    await sequelize.close();
    console.log('迁移完成！');
    
  } catch (error) {
    console.error('迁移失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此文件
if (require.main === module) {
  migrateMissing();
}

module.exports = migrateMissing;
